<template>
  <el-dialog
    v-model="visible"
    title="提交用户反馈"
    width="600px"
    :close-on-click-modal="false"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="反馈类型" prop="feedback_type">
        <el-radio-group v-model="form.feedback_type">
          <el-radio label="correct">确认正确</el-radio>
          <el-radio label="partial">部分正确</el-radio>
          <el-radio label="wrong">完全错误</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label="建议部门"
        prop="suggested_department"
        v-if="form.feedback_type === 'partial' || form.feedback_type === 'wrong'"
      >
        <el-select
          v-model="form.suggested_department"
          placeholder="请选择或输入建议的部门ID"
          filterable
          allow-create
          default-first-option
          style="width: 100%"
        >
          <el-option
            v-for="dept in departmentOptions"
            :key="dept.id"
            :label="`${dept.name} (${dept.id})`"
            :value="dept.id"
          />
        </el-select>
        <div class="form-tip">
          可以从TOP3推理结果中选择，或手动输入其他部门ID
        </div>
      </el-form-item>
      <el-form-item label="反馈说明" prop="feedback_comment">
        <el-input
          v-model="form.feedback_comment"
          type="textarea"
          :rows="4"
          placeholder="请输入反馈说明（可选）"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" :loading="submitting" @click="handleSubmit">
        提交
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from "vue";
import { ElMessage } from "element-plus";
import { submitFeedback } from "../../../servers";

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  assetId: { type: Number, default: null },
  topDepartments: {
    type: Array,
    default: () => [],
  },
});

const emit = defineEmits<{
  (e: "update:modelValue", value: boolean): void;
  (e: "success"): void;
}>();

const visible = computed({
  get: () => props.modelValue,
  set: (value: boolean) => emit("update:modelValue", value),
});

const formRef = ref();
const submitting = ref(false);
const form = ref({
  feedback_type: "correct" as "correct" | "partial" | "wrong",
  suggested_department: "",
  feedback_comment: "",
});

const rules = {
  feedback_type: [
    { required: true, message: "请选择反馈类型", trigger: "change" },
  ],
  suggested_department: [
    {
      required: false,
      validator: (rule: any, value: any, callback: any) => {
        if (
          (form.value.feedback_type === "partial" ||
            form.value.feedback_type === "wrong") &&
          !value
        ) {
          callback(new Error("请选择建议的部门"));
        } else {
          callback();
        }
      },
      trigger: "change",
    },
  ],
};

// 部门选项（从TOP3推理结果中获取）
const departmentOptions = computed(() => {
  return props.topDepartments.map((dept: any) => ({
    id: dept.department_id,
    name: dept.department_name,
  }));
});

// 监听弹窗打开，初始化表单
watch(visible, (newVal) => {
  if (newVal) {
    form.value.feedback_type = "correct";
    form.value.suggested_department = "";
    form.value.feedback_comment = "";
  }
});

// 提交
const handleSubmit = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async (valid: boolean) => {
    if (!valid) return;

    submitting.value = true;
    try {
      const data: any = {
        feedback_type: form.value.feedback_type,
      };
      if (form.value.suggested_department) {
        data.suggested_department = form.value.suggested_department;
      }
      if (form.value.feedback_comment) {
        data.feedback_comment = form.value.feedback_comment;
      }

      await submitFeedback(props.assetId!, data);
      ElMessage.success("反馈提交成功，感谢您的反馈！");
      emit("success");
      emit("update:modelValue", false);
    } catch (error: any) {
      ElMessage.error(error?.message || "提交反馈失败");
    } finally {
      submitting.value = false;
    }
  });
};

// 取消
const handleCancel = () => {
  emit("update:modelValue", false);
};
</script>

<style scoped lang="scss">
.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}
</style>

